import queue
import logging
import threading
import time
import socket
import json
from datetime import datetime

class UdpIn:
    def __init__(self):
        self.run = False
        self.__log_init()

    def __log_init(self):
        self.logger = logging.getLogger("UdpIn")

    def open(self, host, port):
        self.logger.trace('open.enter')

        self.skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8192)
        self.skt.bind((host, port))
        self.skt.settimeout(2)

        self.logger.trace('open.done')
        return True

    def close(self):
        self.logger.trace('close.enter')

        self.skt.close()

        self.logger.trace('close.done')


    def thread(self):
        self.logger.trace('thread.enter')

        while self.run:
            try:
                data, addr = self.skt.recvfrom(1024)
                if not data:
                    continue
                data = data.decode("utf-8")
                self.logger.verbose(f"Received data from {addr}: {data}")
            except socket.timeout:
                # self.logger.spam("Socket timeout, no data received.")
                continue
            except Exception as e:
                self.logger.error(f"An error occurred: {e}")
                continue

            try:
                json_data = json.loads(data)
                self.outqueue1.put(json_data)
                self.logger.verbose(f"Parsed JSON: {json_data}")
            except Exception as e:
                self.logger.error(f"JSON decode error: {e}")
                continue

        self.logger.trace('thread.done')

    def start(self):
        self.logger.trace('start.enter')

        self.run = True
        self.handle = threading.Thread(target=self.thread)
        self.handle.start()

        self.logger.trace('start.done')
        return True

    def stop(self):
        self.logger.trace('stop.enter')
        self.run = False
        self.handle.join()
        self.logger.trace('stop.done')


    def output_queue_set(self, output_queue_list):
        # 设置输出队列，接受的是一个队列列表
        self.logger.trace('output_queue_set.enter')

        if self.run:
            self.logger.error("udpin is opened, please close the udpin first!")
            return False

        if not isinstance(output_queue_list, list):
            output_queue_list = [output_queue_list]

        for output_queue in output_queue_list:
            if not isinstance(output_queue, queue.Queue):
                self.logger.error("one queue is not a queue!")
                return False

        self.outqueue1 = output_queue_list[0] 

        self.logger.trace('output_queue_set.done')
        return True
